package com.xx.lm.webviewloadlocalimg;

import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class WebViewDemo extends AppCompatActivity {

    private WebView webView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_view_demo);
        webView = findViewById(R.id.webview);

        WebSettings webSettings= webView.getSettings();
        //允许webview对文件的操作
//        webSettings.setAllowUniversalAccessFromFileURLs(true);
        webSettings.setAllowFileAccess(true);
//        webSettings.setAllowFileAccessFromFileURLs(true);
        //用于js调用Android
        webSettings.setJavaScriptEnabled(true);
        //设置编码方式
        webSettings.setDefaultTextEncodingName("utf-8");


        String path = "file://"+Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc.png";
        String pp = "file:///sdcard/"+ "/abc.png";
        String html = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "\t<head>\n" +
                "\t\t<meta charset=\"utf-8\" />\n" +
                "\t\t<title></title>\n" +
                "\t</head>\n" +
                "\t<body>\n" +
                "\t\t<p>nimenhao</p>\n" +
                "\t\t\n" +
                "\t\t\n" +
                "\t\t<img src=\"https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png\" />\n" +
                "\t\n" +
                "\t</body>\n" +
                "</html>";

        String html2 = "<!DOCTYPE html>\n" +
                "<html>\n" +
                "\t<head>\n" +
                "\t\t<meta charset=\"utf-8\" />\n" +
                "\t\t<title></title>\n" +
                "\t</head>\n" +
                "\t<body>\n" +
                "\t\t<p>nimenhao</p>\n" +
                "\t\t\n" +
                "\t\t\n" +
                "\t\t<img src=\""+path+"\" />\n" +
                "\t\n" +
                "\t</body>\n" +
                "</html>";

        String html3 = "<!DOCTYPE html>  \n" +
                "<html lang=\"en\">  \n" +
                "<head>  \n" +
                "    <meta charset=\"UTF-8\">  \n" +
                "    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">  \n" +
                "    <title>Title</title>  \n" +
                "</head>  \n" +
                "<body>  \n" +
                "<img id=\"img\" alt=\"上海鲜花港 - 郁金香\" style=\"width: 100%;height: 100%\"/>  \n" +
                "<script>  \n" +
                "function  aa(path){  \n" +
                "alert(path);  \n" +
                " var img=document.getElementById(\"img\");  \n" +
                "    img.src=path;  \n" +
                "}  \n" +
                "  \n" +
                "</script>  \n" +
                "</body>  \n" +
                "</html>  ";

//        String m  = html2.replaceAll("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png",path);

//        int i = html2.indexOf("https://ss0.bdstatic.com/5aV1bjqh_Q23odCf/static/superman/img/logo/bd_logo1_31bdc765.png");


        webView.setWebViewClient(new MyWebViewClient());
//        webView.setWebChromeClient(new chromClient());

        webView.loadData(html,"text/html","utf-8");
//        webView.loadData(m,"text/html","utf-8");
    }

    private void downLoadImg(String url) throws IOException {
        try {
            URL url1 = new URL(url);

            HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
            connection.connect();

            InputStream inputStream = connection.getInputStream();

            String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/abc.png";
            File file = new File(path);
            byte[] a = new byte[1024];

            int  len = -1;
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            while ((len = inputStream.read(a)) != -1){

                fileOutputStream.write(a,0,len);
            }


            inputStream.close();
            fileOutputStream.close();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } finally {

        }


    }

    private class MyWebViewClient extends WebViewClient{
        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
            String key = "https";
            final WebResourceResponse[] response = {null};
            if(url.contains(key)){
                //拿到文件地址
                String imgPath = "abc.png";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                File  file = new File(path,imgPath);
                if (file.exists()){
                    try {
                        FileInputStream inputStream = new FileInputStream(file);

//                            String mimeTypeFromExtension = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));

                        response[0] = new WebResourceResponse("image/png","UTF-8",inputStream);
                        return response[0];
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                }else{

                    try {
                        downLoadImg(url);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
//                    CacheEngine.getInstance().getLocalImgInMain(imgPath)
//                            .subscribe(new Action1<byte[]>() {
//                                @Override
//                                public void call(byte[] bytes) {
//                                    response[0] = new WebResourceResponse("image/png", "UTF-8", new ByteArrayInputStream(bytes));
//                                }
//                            });
                return super.shouldInterceptRequest(view, url);
            }else {
                return super.shouldInterceptRequest(view, url);
            }


//                return super.shouldInterceptRequest(view, url);
        }

        @Override
        public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
            String url = null;
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
                url = request.getUrl().toString();
            }else{

                return super.shouldInterceptRequest(view,request);
            }
            String key = "https";
            final WebResourceResponse[] response = {null};
            if(url.contains(key)){
                //拿到文件地址
                String imgPath = "abc.png";
                String path = Environment.getExternalStorageDirectory().getAbsolutePath();
                File  file = new File(path,imgPath);
                if (file.exists()){
                    try {
                        FileInputStream inputStream = new FileInputStream(file);

//                            String mimeTypeFromExtension = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));

                        response[0] = new WebResourceResponse("image/png","UTF-8",inputStream);
                        return response[0];
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }

                }else{

                    try {
                        downLoadImg(url);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
//                    CacheEngine.getInstance().getLocalImgInMain(imgPath)
//                            .subscribe(new Action1<byte[]>() {
//                                @Override
//                                public void call(byte[] bytes) {
//                                    response[0] = new WebResourceResponse("image/png", "UTF-8", new ByteArrayInputStream(bytes));
//                                }
//                            });
                return super.shouldInterceptRequest(view, request);
            }else {
                return super.shouldInterceptRequest(view, request);
            }
        }
    }


    private class chromClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if(newProgress==100){
                //页面加载完成执行的操作
                String path= "file://"+Environment.getExternalStorageDirectory()+ File.separator+"abc.png";
                String action="javascript:aa('"+path+"')";

                runWebView(action);
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    private void runWebView(final String url){
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                webView.loadUrl(url);
            }
        });
    }

}
